package org.example.demoredis.service.impl;

import org.example.demoredis.entity.Product;
import org.example.demoredis.mapper.ProductMapper;
import org.example.demoredis.service.ProductService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ProductServiceImpl
 * @Description TODO
 * @Author Kx
 * @Date 2025/9/27 15:28
 * @Version 1.0
 */
@Service
public class ProductServiceImpl implements ProductService {
    private final ProductMapper productMapper;
    private final RedisTemplate<String, Product> redisTemplate;

    public ProductServiceImpl(ProductMapper productMapper, RedisTemplate<String, Product> redisTemplate) {
        this.productMapper = productMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Product selectProductById(Integer id) {
        // 判断缓存数据是否为空
        if (!redisTemplate.hasKey("product:" + id)) {
            Product products = productMapper.selectProductById(id);
            redisTemplate.opsForValue().set("product:" + id, products, 1800, TimeUnit.SECONDS);
        }
        return redisTemplate.opsForValue().get("product:" + id);
    }


}
